package com.xxmw.transaction.controller;

import javax.annotation.PostConstruct;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xxmw.transaction.common.entity.P;
import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.model.SysDict;
import com.xxmw.transaction.service.SysDictService;

import java.util.Date;

/**
 * 系统数据字典控制器
 * @author xiangzuotao
 * @2019年11月28日
 */
@RestController
@RequestMapping("/admin/dict")
public class SysDictController {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Autowired
	private SysDictService sysDictService;

	@PostConstruct
	public void init() {
		P<SysDict> result = sysDictService.getSysDictList(1, 500, null);
		result.getRows().forEach(s -> {
			redisTemplate.opsForValue().set(s.getKey(), s.getValue());
		});
	}

	@GetMapping("/list")
	@RequiresPermissions("system:dict:list")
	public R list(@RequestParam(value = "pageNum", defaultValue = "1")Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "20")Integer pageSize,
			@RequestParam(required = false) String key) {
		P<SysDict> p = sysDictService.getSysDictList(pageNum, pageSize, key);
		return R.ok(p);
	}

	@GetMapping("/info")
	@RequiresPermissions("system:dict:info")
	public R info(Integer dictId) {
		SysDict dict = sysDictService.getById(dictId);
		return R.ok(dict);
	}

	@PostMapping("/saveOrUpdate")
	@RequiresPermissions(value = {"system:dict:save", "system:dict:update"}, logical = Logical.OR)
	public R saveOrUpdate(@RequestBody SysDict sysDict) {
		if (null == sysDict.getDictId() || 0 == sysDict.getDictId()) {
			sysDict.setCreated(new Date());
		}
		sysDict.setUpdated(new Date());
		sysDictService.saveOrUpdate(sysDict);
		redisTemplate.opsForValue().set(sysDict.getKey(), sysDict.getValue());
		return R.ok();
	}

	@PostMapping("/delete")
	@RequiresPermissions("system:dict:delete")
	public R delete(@RequestBody Integer[] dictIds) {
		for(Integer dictId : dictIds) {
			SysDict sysDict = sysDictService.getById(dictId);
			redisTemplate.delete(sysDict.getKey());
			sysDictService.removeById(dictId);
		}
		return R.ok();
	}
}
